import { IHttpMsgBody } from "./IHttpMsgBody";

export class HttpUtils
{
    private static _isShowLog: boolean = true;
    public static SyncGet<T>(address: string, params?: {}): Promise<T> {
        return new Promise((resolve, reject) => {
            let xhr: XMLHttpRequest = new XMLHttpRequest();
            let url: string = address + this.ParamsToString(params);
            xhr.open("GET", url, true); // 异步模式

            let interfaceName: string = this.GetUrlInterfaceName(address);
            this._isShowLog && console.log(interfaceName + " url: ", url);

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) { // 请求完成
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                        const data: T = this.GetHttpData(xhr) as T;
                        this._isShowLog && console.log(interfaceName, data);
                        resolve(data);
                    } else {
                        const errorData: T = this.CreateGetErrorData(address, xhr.status) as T;
                        this._isShowLog && console.log(interfaceName + " 错误", errorData);
                        reject(errorData);
                    }
                }
            };

            xhr.send();
        });
    }

    public static Get<T>(address: string, params?: {}, cb?: (value: T) => void): void
    {
        let interfaceName: string = this.GetUrlInterfaceName(address);
        
        let xhr: XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = (ev: Event) =>
        {
            if (xhr.readyState == 4)
            {
                let data: T = null;
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304)
                {
                    data = this.GetHttpData(xhr) as T;
                }
                else
                {
                    data = this.CreateGetErrorData(address, xhr.status) as T;
                }
                this._isShowLog && console.log(interfaceName, data);
                cb && cb(data);
            }
        }

        let url: string = address + this.ParamsToString(params);
        xhr.open("GET", url);
        xhr.send();
        this._isShowLog && console.log(interfaceName + " url: ", url);
    }

    public static ParamsToString (params: any): string
    {
        let arr: string[] = [];
        for (let key in params)
        {
            arr.push(key + "=" + params[key]);
        }
        if (arr.length > 0)
        {
            return `?${arr.join("&")}`;
        }
        
        return "";
    }

    public static GetHttpData(xhr: XMLHttpRequest): any
    {
        let outData: any = {};
        try
        {
            outData = JSON.parse(xhr.response);
        }
        catch (err)
        {
            outData = xhr.response;
        }

        return outData;
    }

    public static GetUrlInterfaceName (url: string): string
    {
        let adress: string = url.split("?")[0];
        let strArr: string[] = adress.split("/");
        return strArr[strArr.length - 1];
    }

    public static CreateGetErrorData (address: string, status: number): IHttpMsgBody.IResBase
    {
        let interfaceName: string = this.GetUrlInterfaceName(address);
        let resData: IHttpMsgBody.IResBase = {} as IHttpMsgBody.IResBase;
        resData.code = status;
        resData.docs = `${interfaceName} status: ${status}`;
        return resData;
    }
}